package skdao

import (
	"Cgo/backend/models"
	"Cgo/global"
	"errors"
)

type bookDao struct{}

var BookDao = bookDao{}

// 添加书籍
func (b bookDao) AddBook(bookId int, bookName string, Autor string, Type string, state string, bookurl string) error {
	// 执行数据库插入操作
	if result := global.DB.Exec("INSERT INTO sk_book (bookid, bookname, autor,type,state,bookurl) VALUES (?, ?, ?, ?, ?, ?)", bookId, bookName, Autor, Type, state, bookurl); result.Error != nil {
		return result.Error
	} else {
		return nil
	}
}

// 修改书籍信息
func (b bookDao) UpdateBook(book models.SkBook) error {
	// 检查书籍是否存在
	var bookInfo models.SkBook
	if r := global.DB.Raw("SELECT * FROM sk_book WHERE bookid = ?", book.Bookid).Scan(&bookInfo); r.RowsAffected == 0 {
		return errors.New("书籍不存在")
	}

	// 更新书籍信息
	if err := global.DB.Save(&book).Error; err != nil {
		return err
	}

	return nil
}

// 删除书籍
func (b bookDao) DeleteBook(bookId int) error {
	if r := global.DB.Exec("DELETE FROM sk_book WHERE bookId = ?;", bookId); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}

// GetBooks 用于获取所有书籍信息(刷新)
func (b bookDao) GetBooks() ([]models.SkBook, error) {
	var books []models.SkBook
	if err := global.DB.Table("sk_book").Find(&books).Error; err != nil {
		return nil, err
	}
	return books, nil
}
